<?php

namespace App\Model\Business;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Appointment extends Model
{
    # 数据表
    protected $table = 'appointments';

    # PK
    protected $primaryKey = 'appointid';

    # fillable fields
    protected $fillable = [
        'status',
        'studentuid',
        'studentname',
        'mobile',
        'classhours',
        'classbonus',
        'courseid',
        'coursename',
        'orderdate',
        'description',
        'amount',
        'orderid'
    ];


    public static function getAll(Request $request)
    {
        $query = DB::table('appointments as app')
                 ->join('students', 'students.studentuid', '=', 'app.studentuid');
        if($request->has('status')) {
            $status = intval($request->get('status'));
            $query->where('app.status',  $status);
        }
        # 构造查询条件
        if($request->has('studentname')) {
            $name = "%{$request->studentname}%";
            $query->orwhere('app.studentname', 'like', $name);
        }
        if($request->has('ClassIn')) {
            $ClassIn = "%{$request->ClassIn}%";
            $query->orwhere('students.ClassInNo', 'like', $ClassIn);
        }
        # 需要／不需要 分页
        if($request->has('page')) {
            $limit = 30;
            if ($request->has('perPage')) {
                $limit = $request->get('perPage');
            }
            $items = $query->paginate($limit)->toarray();
        }else{
            $items = $query->get()->toarray();
        }
        return $items;
    }

    /**
     * 预约
     */
    public function appoint($value=1)
    {
        $this->increment('consumed', $value);
        $this->save();
    }

    /**
     * 取消预约
     */
    public function unppoint($value=1)
    {
        $this->decrement('consumed', $value);
        $this->save();
    }

}

